/*
#proc.c
#
*/
#include <types.h>
#include <i386.h>
#include <cpumtsk.h>
#include <task.h>
#include <intr.h>

void proc1();
void proc2();
void idle();
uint8 cur_task = 0;


void tss_init(){
	struct seg_descriptor_t tssdescr;
	kprintf("size: %X\n", sizeof(tsspercpu[0]));
	tssdescr.sd_lolimit = sizeof(tsspercpu[0]);
	tssdescr.sd_lobase = (&(tsspercpu[0]));
	tssdescr.sd_type = SD_486TSS_AC;
	tssdescr.sd_dpl = SPL;
	tssdescr.sd_present = 1;
	tssdescr.sd_hilimit = sizeof(tsspercpu[0]) >> 16;
	tssdescr.sd_xavl = 0;
	tssdescr.sd_defsz = 0;
	tssdescr.sd_gran = 0;
	tssdescr.sd_hibase = ((uint32)(&(tsspercpu[0]))) >> 24;
	//tssdescr.sd_hilimit = 
	setdescriptor(tssdescr, 16);
	
	uint16 ss0;
	uint32 cr3;
	tsspercpu[0].endbyte = 0xFF;
	tsspercpu[0].esp0 = (uint32)proc_stack;
	kprintf("EPS0: %X\n", tsspercpu[0].esp0);
	asm("movw %ss, %ax");
	asm("movw %%ax, %0":"=r"(ss0)::"%ax");
	tsspercpu[0].ss0 = ss0;
	kprintf("ss=%X\n", tsspercpu[0].ss0);
	asm("movl %%cr3, %0":"=r"(cr3)::"%eax");
	tsspercpu[0].cr3 = cr3;
	kprintf("cr3=%X\n", tsspercpu[0].cr3);
	asm("pushfl");
	asm("popl %0;":"=r"(cr3)::"%eax");
	tsspercpu[0].eflags = cr3;
	tsspercpu[0].eip = (uint32)proc1;	
}

init_proc(uint32 proc, uint32 proc_stack, uint32 pde){
	
}



unsigned int start_proc0(){
	//alloc_user_page();
	pr_tlb_head = pr_tlb;
	pr_tlb[0].nextp = &pr_tlb[1];
	pr_tlb[1].nextp = &pr_tlb[0];
	

	pr_tlb[0].stk = proc_stack;
	pr_tlb[1].stk = proc_stack2;
	
	uint32 i;
	for(i = 0; i < 1024; i++){
		pr_tlb[0].stk[i] = 0;
		pr_tlb[1].stk[i] = 0;
	}
	kprintf("pr1stack: %X\n", (uint32)pr_tlb[0].stk);
	kprintf("pr2stack: %X\n", (uint32)pr_tlb[1].stk);
	//uint32 z;
	//for(z = 0; z < 1024; z++){
	//	proc_stack2[z] = 0;
	//}
	
	pr_tlb[0].esp = (uint32)(pr_tlb[0].stk) + 4096;
	pr_tlb[0].eip = (uint32)proc1;
	pr_tlb[0].state = 0;
		
	pr_tlb[1].esp = (uint32)(pr_tlb[1].stk) + 4096;
	pr_tlb[1].eip = (uint32)proc2;
	pr_tlb[1].state = 0;
	
	
	kprintf("esp: %X - %X\n", pr_tlb[1].esp, (uint32)(pr_tlb[1].stk));
	
	//get_gdtr();
	kprintf("gdtable: %X\n", (uint32)gdtable);
	
	printsegaddr(0);
	printsegaddr(12);
	printsegaddr(13);
	intr_on();
	//for(;;);
	asm("jmp _idle;");
	return 0;
}

void proc1(){
	uint32 i = 0, c = 0;
	for(i = 0;;i++){
		if(i == 1000000){
			//asm("mov %%ds, %0":"=r" (c)::"eax");
			
			//kprintf("A:%X:", c);
			kprintf("A");
			i = 0;
			//c++;
			//if(c == 5) c = 0;
		}
	}
}
void proc2(){
	//asm("mov %ax, %bx");
	uint32 i = 0, c = 0;
	for(i = 0;;i++){
		if(i == 1000000){
			kprintf("B");
			i = 0;
			//c++;
			//if(c == 5) c = 0;
		}
	}
}

void idle(){
	asm("_idle:");
	uint32 i = 0;
	for(i = 0;;i++){
		if(i == 1000000){
			kprintf(".");
			i = 0;
		}
	}
}







